
import { unionBy } from 'lodash-es';
import { message } from 'ant-design-vue'
import { $each } from '@/utils/index';
import { isNullOrEmpty } from "@/utils/is";
import worldMapData from '@/utils/json/world.json';
import { get } from '@/utils/http/Axios';
import { areaMapNames } from '@/utils/constant/map';
// 已配置下钻
function checkConfiguration(list = []) {
  return list && list.length;
}

// 可以继续下钻
function checkContinue(list = [], drillBreadcrumbsPreview) {
  return drillBreadcrumbsPreview.length < list.length;
}

// 触发下钻
export function clickChartHandleDrillData(params, relation_block = {}, drillBreadcrumbsPreview, cbs) {
  const { name, seriesType, values, xAxisName, componentsName } = params;
  const { relationData } = relation_block;
  const { drillInfo, fields } = relationData || {};
  let finalName = name;
  // 因为地图需要同时触发下钻和联动，所以需要记录下下钻状态
  let isMapDrillState = true;
  // 地图默认支持下钻，即使不配置下钻信息
  if (seriesType !== 'map') {
    // 当前被点击的一项
    if (!checkConfiguration(drillInfo?.list)) {
      cbs && cbs('error');
      return;
    }
    // 不能继续下钻
    if (drillInfo?.list.length === 1 || !checkContinue(drillInfo?.list, drillBreadcrumbsPreview.value)) {
      message.warning('已经钻取到最后一层了！');
      cbs && cbs('error');
      return false;
    }
  } else {
      finalName = name === 'China' ? '中国' : name;
      if (!areaMapNames[finalName] && finalName !== '中国') {
        isMapDrillState = false;
        message.warning('暂无该地区数据');
        cbs && cbs('error');
      } else {
        // 地图类型需要更换下钻地图
        const params = {
          mapName: finalName === '中国' ? 'country-100000' : areaMapNames[finalName],
          componentsName,
          values,
        };
        changeMap(params, cbs);
      }
  }

  if (isMapDrillState) {
    // 下钻需要生成面包屑 下钻A -> 下钻B -> 下钻C
    generateBreadcrumb({
      name: finalName,
      seriesType,
      values,
      xAxisName,
      fields,
      drillBreadcrumbsPreview,
    });
    if (seriesType!== 'map') {
      cbs && cbs();
    }
  }
}

// 生成面包屑逻辑
function generateBreadcrumb({ name, seriesType, values, xAxisName, fields, drillBreadcrumbsPreview }) {
  /*
   * 判断是否是第一个, 默认要添加第一级
   */
  if (drillBreadcrumbsPreview.value.length === 0) {
    // 从配置的下钻维度列表中拿出第一个维度名称
    const breadcrumbHeader = { label: xAxisName };
    let mapHeader = [];
    // 地图添加的是地图名称
    if (seriesType === 'map') {
      mapHeader = [
        {
          label: '世界',
          type: 'map',
          value: 'world',
        },
        {
          label: '中国',
          type: 'map',
          value: 'China',
        },
      ];
    }

    // 添加默认第一级
    if (seriesType === 'map') {
      drillBreadcrumbsPreview.value.push(...mapHeader);
    } else {
      drillBreadcrumbsPreview.value.push(breadcrumbHeader);
    }
  }

  // 定义面包屑默认值
  const breadcrumb = { label: undefined };

  if (['table', 'map'].includes(seriesType)) {
    breadcrumb.label = seriesType === 'map' ? name : values[0];
  } else {
    // 获取下钻绑定的维度
    const dimension = getDimensionWithDrill(fields);
    // 根据维度配置和钻取配置
    const { index } = dimension;
    if (!isNullOrEmpty(index)) {
      breadcrumb.label = values[index];
    }
  }

  // 地图的需要添加type做上钻逻辑
  if (seriesType === 'map') {
    breadcrumb.type = seriesType;
    breadcrumb.value = areaMapNames[breadcrumb.label];
  }
  // 添加面包屑
  drillBreadcrumbsPreview.value.push(breadcrumb);
  seriesType === 'map' && (drillBreadcrumbsPreview.value = unionBy(drillBreadcrumbsPreview.value, 'label'))
}

// 触发上钻
export function triggerHandleDrillUp({ index, item }, drillBreadcrumbsPreview, cbsUp) {
  // 地图的话需要进行图形切换
  const breadcrumb = drillBreadcrumbsPreview.value[index];
  // charts为地图，需要更新
  if (breadcrumb && breadcrumb.type === 'map') {
    // 更改下钻地图
    if ((item && item.value === 'China')) {
      changeMap({ seriesType: 'map', mapName: 'country-100000' }, cbsUp);
    } else {
      changeMap({ seriesType: breadcrumb.type, mapName: breadcrumb.value }, cbsUp);
    }
  } else {
    cbsUp && cbsUp();
  }
}

// 这里更新地图的options/series还是 geo对象单元
function changeMap({ mapName, componentsName, _values }, cbs) {
  const params = mapName && [...mapName.split('-').slice(0, 1), ...mapName.split('-').slice(1)];
  // 处理数据，强制更新
  commonGetMapChartJSON(params, cbs);
}

// 获取开启下钻标识的维度
function getDimensionWithDrill(fields) {
  const {
    xAxis: { relations = [] },
  } = fields;
  let dimension = {},
    i = 0;
  $each(relations, (item) => {
    // 开启下钻标识
    if (item.isDrilled) {
      dimension = { column: item.datasetFieldName, index: i };
    }
    i++;
  });

  return dimension;
}

/**
 *
 * @param block
 * @param result
 */
export function commonGetMapChartJSON(result, callBack) {
  const [country, province, city] = result;
  const mapId = city || province;
  if (country !== 'world') {
    get(`/gis/api/v1/areas/bound/${mapId}_full`).then((response) => {
      return response;

    }).then(jsonType => {
      if (jsonType) {
        // 判断地图是否存在,是否有变化
        callBack && callBack(jsonType, result);
      }
    });
  } else {
      // 世界地图叫world
      callBack && callBack(worldMapData, 'world');
  }
}
